package Pack;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class Principal implements ActionListener, KeyListener, MouseListener{
	private JFrame frame,frameCadastro;
	private JPanel wrapper;
	private JMenuBar menuBar, statusBar;
	private JMenu menuArquivo;
	private JMenuItem itemSair,itemCadastro;	
	private final String STRING_VAZIA = "";
	
	private Principal(){
		frame = new JFrame("Janela");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		wrapper = new JPanel();
		menuBar = new JMenuBar();
		menuArquivo = new JMenu("Arquivo");
		statusBar = new JMenuBar();
		itemSair = new JMenuItem("Sair");
		itemCadastro = new JMenuItem("Cadastro");
		frameCadastro = new JFrame("Cadastro");		
	}
	
	private void iniciar(){
		frame.setVisible(true);
		frame.setSize(800,600);
		frame.setMinimumSize(new Dimension(800,600));
		frame.setLayout(new BorderLayout());
		JPanel wrapper = new JPanel();
		wrapper.setBackground(Color.black);
		wrapper.setLayout(new BorderLayout());
		ImageIcon background = new ImageIcon("imagens/background.jpg");
		wrapper.add(new JLabel(background), BorderLayout.CENTER);
		
		menuArquivo.add(itemCadastro);
		menuArquivo.add(new JSeparator());
		menuArquivo.add(itemSair);
		statusBar.add(new JLabel("v1.0"));
		menuBar.add(menuArquivo);
		frame.add(menuBar, BorderLayout.PAGE_START);
		frame.add(wrapper, BorderLayout.CENTER);
		frame.add(statusBar, BorderLayout.SOUTH);
		
		//Seta para cada botao seus respectivos listeners
		setListeners();
		
		//Frame de cadastro
		constroiJanelaCadastro();
	}
	
	//Atributos da janela de cadastro
	private JLabel lbFoto,btCadastroCadastrar,btCadastroCancelar;
	private String urlFoto;
	private JTextField nome,dataNascimento,telefone,email,endereco;
		
	private void verificaFoto(){
		if(new File("imagens/fotoPerfil.jpg").exists()){
			urlFoto = "imagens/fotoPerfil.jpg";
			return;
		}
		urlFoto = "imagens/foto.jpg";
	}
	
	private void resetaCadastro(){
		nome.setText("");
		dataNascimento.setText("");
		telefone.setText("");
		email.setText("");
		endereco.setText("");
	}
	
	private Perfil cadastra() throws Exception{
		Perfil temp = new Perfil();
		String nome, email;
		if(!this.nome.getText().equals(STRING_VAZIA) && !this.email.getText().equals(STRING_VAZIA)){
			nome = this.nome.getText();
			email = this.email.getText();
			temp = new Perfil(nome,email);
			temp.setTelefone(this.telefone.getText());
			temp.setDataNascimento(this.dataNascimento.getText());
			temp.setEndereco(this.endereco.getText());
		}else{
			if(this.nome.getText().equals(STRING_VAZIA)){
				throw new Exception("Digite um nome!");
			}else if(this.email.getText().equals(STRING_VAZIA)){
				throw new Exception("Digite um email");
			}
		}
		return temp;
	}
	
	/*
	 * Constroi janela Cadastro
	 */
	private void constroiJanelaCadastro(){
		frameCadastro.setVisible(false);
		frameCadastro.setResizable(false);
		frameCadastro.setSize(500, 500);
		frameCadastro.setLocationRelativeTo(frame);
		
		JPanel wrapper = new JPanel();
		wrapper.setLayout(new BoxLayout(wrapper,BoxLayout.LINE_AXIS));
		frameCadastro.add(wrapper);
		
		JPanel p1 = new JPanel(), p2 = new JPanel(),pFoto = new JPanel();
		p2.setBackground(Color.white);
		pFoto.setLayout(new BorderLayout());
		pFoto.setBackground(Color.white);
		p2.setLayout(new FlowLayout(FlowLayout.CENTER));
		p1.setLayout(new GridLayout(13,1));
		p1.setBackground(Color.white);
		p1.setBorder(BorderFactory.createEmptyBorder(0, 10, 5, 10));
		wrapper.add(p2);
		wrapper.add(p1);
		
		verificaFoto();
		
		ImageIcon img = new ImageIcon(urlFoto);

		lbFoto = new JLabel(img);
		lbFoto.setBorder(BorderFactory.createMatteBorder(1,1,5,1,Color.decode("200200200")));
		lbFoto.addMouseListener(this);
	
		pFoto.add(lbFoto, BorderLayout.PAGE_START);
		pFoto.add(new JLabel("Clique para mudar a foto"));
		p2.add(pFoto);
				
		nome = new JTextField("",20);
		nome.setToolTipText("Digite seu nome");
		nome.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.DARK_GRAY));
		dataNascimento = new JTextField("",12);
		dataNascimento.setToolTipText("dd/mm/aaaa");
		dataNascimento.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.DARK_GRAY));
		email = new JTextField("",20);
		email.setToolTipText("fulano@servidor");
		email.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.DARK_GRAY));
		telefone = new JTextField("",10);
		telefone.setToolTipText("5555-0123");
		telefone.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.DARK_GRAY));
		endereco = new JTextField("",30);
		endereco.setToolTipText("Digite seu endereco");
		endereco.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.DARK_GRAY));
		
		JLabel lbNome, lbDataNascimento, lbTelefone, lbEmail, lbEndereco; 
		lbNome = new JLabel("<html><font Color='#FF4500'>*</font> Nome:</html>");lbNome.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.decode("200200200")));
		lbDataNascimento = new JLabel("Data de Nascimento:");lbDataNascimento.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0,Color.decode("200200200")));
		lbEmail = new JLabel("<html><font Color='#FF4500'>*</font> Email:</html>");lbEmail.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.decode("200200200")));
		lbTelefone = new JLabel("Telefone:");lbTelefone.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.decode("200200200")));
		lbEndereco = new JLabel("Endereco:");lbEndereco.setBorder(BorderFactory.createMatteBorder(0, 0, 2, 0, Color.decode("200200200")));
		
		p1.add(lbNome);p1.add(nome);
		p1.add(lbDataNascimento);p1.add(dataNascimento);
		p1.add(lbEmail);p1.add(email);
		p1.add(lbTelefone);p1.add(telefone);
		p1.add(lbEndereco);p1.add(endereco);
		p1.add(new JLabel("<html><font Color='#FF4500' size='2'><b>* Item Obrigatorio!</html>"));
				
		JPanel pButton = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		pButton.setBackground(Color.white);
		btCadastroCadastrar = new JLabel("<html><font size=3>Cadastrar</html>");
		btCadastroCadastrar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.orange));
		btCadastroCancelar = new JLabel("<html><font size=3> Cancelar </html>");
		btCadastroCancelar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.orange));
		pButton.add(btCadastroCadastrar);
		pButton.add(btCadastroCancelar);
		p1.add(pButton);
		
		btCadastroCadastrar.addMouseListener(this);
		btCadastroCancelar.addMouseListener(this);
	}
	
	/*
	 * Seta os listeners dos botoes
	 */
	private void setListeners(){
		itemSair.addActionListener(this);
		itemSair.addKeyListener(this);
		itemSair.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,KeyEvent.ALT_MASK));
		itemCadastro.addActionListener(this);
		itemCadastro.addKeyListener(this);
		itemCadastro.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,KeyEvent.ALT_MASK));

	}

	
	public static void main(String[] args) {
		Principal janela = new Principal();
		janela.iniciar();
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		// TODO Auto-generated method stub
		if(event.getSource() == itemCadastro){
			frameCadastro.setVisible(true);
		}else if(event.getSource() == itemSair){
			System.exit(0);
		}
	}

	@Override
	public void keyPressed(KeyEvent event) {
		if(event.getSource()==itemCadastro){
			frameCadastro.setVisible(true);
		}else if(event.getSource() == itemSair){
			System.exit(0);
		}
		
	}

	@Override
	public void keyReleased(KeyEvent event) {
			
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseClicked(MouseEvent event) {
		if(event.getSource() == lbFoto){
			JFileChooser fileChooser = new JFileChooser();
			if(fileChooser.showOpenDialog(frameCadastro) == JFileChooser.APPROVE_OPTION){
				try{
					BufferedImage imagem = ImageIO.read(fileChooser.getSelectedFile());		
					int novaLargura = 150, novaAltura = 150;
					BufferedImage new_img = new BufferedImage(novaLargura,novaAltura, BufferedImage.TYPE_INT_RGB);
					Graphics2D g = new_img.createGraphics();
					g.drawImage(imagem, 0, 0, novaLargura,novaAltura, null);
					ImageIO.write(new_img, "JPG", new File("imagens/fotoPerfil.jpg"));				
					urlFoto = "imagens/fotoPerfil.jpg";
					lbFoto.setIcon(new ImageIcon(urlFoto));
					frameCadastro.repaint();
				}catch(IOException erro){
					System.out.println(erro.getMessage());
				}
			}
		}
		
	}

	@Override
	public void mouseEntered(MouseEvent event) {
		if(event.getSource() == btCadastroCadastrar){
			btCadastroCadastrar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.blue));
		}else if(event.getSource() == btCadastroCancelar){
			btCadastroCancelar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.blue));
		}
		
	}

	@Override
	public void mouseExited(MouseEvent event) {
		if(event.getSource() == btCadastroCadastrar){
			btCadastroCadastrar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.orange));
		}else if(event.getSource() == btCadastroCancelar){
			btCadastroCancelar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.orange));
		}
		
	}

	@Override
	public void mousePressed(MouseEvent event) {
		if(event.getSource() == btCadastroCadastrar){
			btCadastroCadastrar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.black));
			Perfil newPerfil;
			try {
				newPerfil = cadastra();
				JOptionPane.showMessageDialog(frameCadastro, newPerfil);
				frameCadastro.setVisible(false);
			} catch (Exception e) {
				JOptionPane.showMessageDialog(frameCadastro, e.getMessage(),"Campo vazio", JOptionPane.WARNING_MESSAGE);
			}			
		}else if(event.getSource() == btCadastroCancelar){
			btCadastroCancelar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.black));
			frameCadastro.setVisible(false);
			resetaCadastro();
		}		
	}

	@Override
	public void mouseReleased(MouseEvent event) {
		if(event.getSource() == btCadastroCadastrar){
			btCadastroCadastrar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.DARK_GRAY));
		}else if(event.getSource() == btCadastroCancelar){
			btCadastroCancelar.setBorder(BorderFactory.createMatteBorder(0, 0, 3, 0, Color.DARK_GRAY));
		}
		
	}
}
